﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.System.AppNotice
{
    [UseDI(ServiceLifetime.Scoped)]
    public class AppNoticeInfoRepostitory : Repository<AppNoticeInfo, DefaultDbContext>
    {
        public AppNoticeInfoRepostitory(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public IPagedList<AppNoticeInfo> GetAppNoticeInfos(AppNoticeInfoQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("app_notice_info");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(title Like @0 or content like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.NoticeType.HasValue)
                sql.Where("notice_type =@0", (int)query.NoticeType);
            sql.Where("is_deleted=0");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        /// <summary>
        /// 获取所有有效数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<AppNoticeInfo> GetAppNoticeInfos()
        {
            Sql sql = Sql.Builder;
            sql.Select("id").From("app_notice_info").Where("is_deleted=0");
            var ids = DbContext.FetchFirstColumn<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}